package com.atguigu.config;

import com.atguigu.entity.Admin;
import com.atguigu.service.AdminService;
import com.atguigu.service.PermissionService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @DubboReference
    private AdminService adminService;

    @DubboReference
    private PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Admin admin = adminService.getByUsername(username);
        if(null == admin) {
            throw new UsernameNotFoundException("用户名不存在！");
        }
//        获取用户的所有权限码
        List<String> codeList = permissionService.findCodeListByAdminId(admin.getId());
//        准备一个collection，封装权限码
        Collection<GrantedAuthority> authorities = new ArrayList<>();
//       迭代codelist
        for (String code : codeList) {
            if (!StringUtils.isEmpty(code)) {
                SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(code);
                authorities.add(simpleGrantedAuthority);
            }
        }
        return new User(username,admin.getPassword(),authorities);
    }
}
